﻿using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace EzFrameWork
{
    public class EzTCPClient
    {
        private TcpClient _client;
        private Thread receiveT;
        private Thread HertThread;
        byte[] data;
        private string url;
        private int port;
        public string IDText = "";
        public Action<MessageType, byte[]> Response;

        private bool isOnline = false;

        public bool IsOnline
        {

            get
            {
                return isOnline;
            }

            private set
            {
                isOnline = value;
            }

        }
        public EzTCPClient(string ULR, int Port)
        {
            url = ULR;
            port = Port;
        }
        public void ShowOnGUI()
        {
            GUI.Label(new Rect(0, 0, 200, 80), IsOnline ? "在线" : "离线");
            
        }

        //开始链接
        public void OpenLink()
        {
            Connet(url, port);
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        public void CloseLink()
        {
            isOnline = false;
            if (receiveT != null)
            {
                receiveT.Abort();
            }
            if (_client != null)
            {
                _client.Client.Close();
            }
            _client = null;
            receiveT = null;
            Debug.Log("主动断开链接");
            if (HertThread != null)
            {
                HertThread.Abort();//停止发送心跳包
            }
        }

        private void Connet(string url, int portNo)
        {
            try
            {
                this._client = new TcpClient();
                this._client.Connect(url, portNo);
                data = new byte[1024 * 1024];
                receiveT = new Thread(ReceiveMsg);
                receiveT.Start();
                SendMessages("连接成功 LinK OK", MessageType.TEXT);
                HertThread = new Thread(SendHertToSever);//开始发送心跳包
                HertThread.Start();
                isOnline = true;
            }
            catch (System.Exception e)
            {
                Debug.Log(e);
                isOnline = false;
            }
        }
        private void ReceiveMsg()
        {
            while (true)
            {
                try
                {
                    NetworkStream netStream = new NetworkStream(_client.Client);
                    byte[] datasize = new byte[4];
                    netStream.Read(datasize, 0, 4);
                    int size = System.BitConverter.ToInt32(datasize, 0);
                    byte[] message = new byte[size];
                    int dataleft = size;
                    int start = 0;
                    while (dataleft > 0)
                    {
                        int recv = netStream.Read(message, start, dataleft);
                        start += recv;
                        dataleft -= recv;
                    }
                    if (message.Length > 0)
                    {
                        MessageAgreement.ReadSimpleDataPack(message, (T, D) =>
                         {
                             if (Response != null)
                             {
                                 Response(T, D);
                             }
                         });
                    }
                }
                catch (Exception e)
                {
                    Debug.Log("与服务器断开链接:" + e);
                    CloseLink();
                }
            }
        }

        //发送字符串类型的消息
        public void SendMessages(string message, MessageType messageType)
        {
            try
            {
                NetworkStream ns = this._client.GetStream();
                byte[] temp = MessageAgreement.WriteSimpleDataPack(message, messageType);
                ns.Write(temp, 0, temp.Length);
                ns.Flush();
                isOnline = true;
            }
            catch (Exception ex)
            {
                Debug.Log(ex);
                isOnline = false;
                CloseLink();
            }
        }

        //发送byte[] 类型的消息
        public void SendMessages(byte[] message, MessageType messageType)
        {
            try
            {
                NetworkStream ns = this._client.GetStream();
                byte[] temp = MessageAgreement.WriteSimpleDataPack(message, messageType);
                ns.Write(temp, 0, temp.Length);
                ns.Flush();
                isOnline = true;
            }
            catch (Exception ex)
            {
                Debug.Log(ex);
                CloseLink();
            }
        }

        /// <summary>
        /// 发送心跳包
        /// </summary>
        private void SendHertbyThread()
        {
            if (IDText != null)
            {
                Hert h = new Hert();
                h.ID = IDText;//获取本机ID
                h.Time = DateTime.Now;
                byte[] hertData = EzDataRWS.ObjectToBytes(h);
                SendMessages(hertData, MessageType.HERTPACK);
                Debug.Log("客户端发送心跳包");
            }
        }

        private void SendHertToSever()
        {
            Debug.Log("开始发送心跳包");
            while (_client.Connected)
            {
                Thread.Sleep(1000);//每隔一秒发送一次心跳包
                SendHertbyThread();
                Debug.Log("发送了心跳包");
            }
            Debug.Log("停止发送心跳包");
        }


    }
}